<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <link rel="stylesheet" href="/layui/css/layui.css" media="all">
</head>
<body>
<form class="layui-form" lay-filter="commodity">
  <div id="id" class="layui-form-item">
    <label class="layui-form-label">id</label>
    <div class="layui-input-inline">
      <input readonly type="text" name="id" autocomplete="off" class="layui-input">
    </div>
  </div>


  <div class="layui-form-item">
    <label class="layui-form-label">商品名称</label>
    <div class="layui-input-inline">
      <input type="text" name="name" placeholder="请输入商品名称" required lay-verify="required" autocomplete="off"
             class="layui-input">
    </div>
  </div>


  <div class="layui-form-item">
    <label class="layui-form-label">商品编码</label>
    <div class="layui-input-inline">
      <input type="text" name="code" placeholder="请输入编码" required lay-verify="required" autocomplete="off"
             class="layui-input">
    </div>
  </div>


  <div class="layui-form-item">
    <label class="layui-form-label">商品单价(元)</label>
    <div class="layui-input-inline">
      <input type="text" name="price" required lay-verify="required|money" placeholder="请输入价格" autocomplete="off"
             class="layui-input">
    </div>
  </div>

  <div class="layui-form-item">
    <label class="layui-form-label">商品图片</label>
    <div class="layui-input-inline">
      <input type="text" id="imageInput" name="image" autocomplete="off" class="layui-input layui-hide">
      <div class="layui-upload">
        <button type="button" class="layui-btn" id="upload">上传图片(最佳为200*200)</button>
        <div class="layui-upload-list">
          <img style="width: 200px;height: 200px" class="layui-upload-img" id="image">
          <p id="text"></p>
        </div>
      </div>
    </div>
  </div>


  <div class="layui-form-item">
    <label class="layui-form-label">店铺</label>
    <div class="layui-input-inline">
      <select id="shop" name="shopId" required lay-verify="required" lay-filter="county">
        <option value="">请选择</option>
      </select>
    </div>
  </div>

  <div class="layui-form-item">
    <label class="layui-form-label">是否上架</label>
    <div class="layui-input-inline">
      <input type="checkbox" name="state" value="PUT_AWAY" lay-skin="switch" lay-text="是|否" checked>
    </div>
  </div>

  <div class="layui-form-item layui-form-text">
    <label class="layui-form-label">商品主料</label>
    <div class="layui-input-block">
      <textarea name="mainIngredient" placeholder="请输入" class="layui-textarea"></textarea>
    </div>
  </div>

  <div class="layui-form-item layui-form-text">
    <label class="layui-form-label">商品辅料</label>
    <div class="layui-input-block">
      <textarea name="ingredients" placeholder="请输入" class="layui-textarea"></textarea>
    </div>
  </div>

  <div class="layui-form-item layui-form-text">
    <label class="layui-form-label">备注</label>
    <div class="layui-input-block">
      <textarea name="remark" placeholder="请输入" class="layui-textarea"></textarea>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-input-block">
      <button id="insert" class="layui-btn" lay-submit lay-filter="insert">立即提交</button>
      <button id="update" class="layui-btn" lay-submit lay-filter="update">立即提交</button>
      <button id="reset" type="reset" class="layui-btn layui-btn-primary">重置</button>
    </div>
  </div>
</form>
<script src="/layui/layui.js" charset="utf-8"></script>
<script src="/jquery/jquery-3.5.1.min.js"></script>
<script>
  // 先初始化
  layui.use(['form', 'layer', 'upload'], function () {
    const form = layui.form;
    const layer = layui.layer;
    const upload = layui.upload;

    $.ajaxSettings.async = false;
    $.get("/api/shop/list", function (data) {
      data = data.data;
      console.log(data);
      for (let i = 0; i < data.length; i++) {
        const item = data[i];
        $('#shop').append("<option value='" + item.id + "'>" + item.name + "(" + item.code + ")</option>")
      }
      form.render('select');
    });
    $.ajaxSettings.async = true;

    form.verify({
      money: function (value) {//value：表单的值、item：表单的DOM对象
        if (!value.includes('.')) {
          // 加上小数后缀
          value = value + ".00";
        }
        const reg = new RegExp('^(([1-9][0-9]{0,14})|([0])|(([0]\\.\\d{1,2}|[1-9][0-9]{0,14}\\.\\d{1,2})))$');
        if (!reg.test(value)) {
          return '请输入合法的金额';
        }
      }
    });

    const uploadInst = upload.render({
      elem: '#upload',
      accept: 'images', //只允许上传图片
      acceptMime: 'image/*', //只筛选图片
      url: '/api/file/upload/', //改成您自己的上传接口
      before: function (obj) {
        //预读本地文件示例，不支持ie8
        obj.preview(function (index, file, result) {
          $('#image').attr('src', result); //图片链接（base64）
        });
      },
      done: function (res) {
        //如果上传失败
        if (res.code !== 200) {
          return layer.msg('上传失败');
        } else {
          $("#imageInput").val(res.data)
          return layer.msg('上传成功')
        }
        //上传成功
      },
      error: function () {
        //演示失败状态，并实现重传
        const text = $('#text');
        text.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs reload">重试</a>');
        text.find('.reload').on('click', function () {
          uploadInst.upload();
        });
      }
    });

    // 新增
    form.on('submit(insert)', function (data) {
      const params = JSON.stringify(data.field);
      console.log(params);

      $.ajax({
        url: "/api/commodity",
        method: 'post',
        contentType: 'application/json',
        data: params,
        dataType: 'json',
        success: function (data) {
          if (data.code === 200) {
            layer.msg('添加成功')
            // 1秒后刷新
            setTimeout(function () {
              window.parent.location.reload();
            }, 1500);
          } else if (data.code === 100) {
            layer.msg(data.message);
          }
        }
      });
      return false;
    });
    // 修改
    form.on('submit(update)', function (data) {
      const params = JSON.stringify(data.field);
      const id = data.field.id;
      $.ajax({
        url: "/api/commodity/" + id,
        method: 'put',
        contentType: 'application/json',
        data: params,
        dataType: 'json',
        success: function (data) {
          if (data.code === 200) {
            layer.msg('修改成功')
            setTimeout(function () {
              window.parent.location.reload();
            }, 1500);
          } else if (data.code === 100) {
            layer.msg(data.message);
          }
        }
      });
      return false;
    })
  });

  // 最后赋值
  function formData(data) {
    layui.use(['form', 'layer'], function () {
      const form = layui.form;
      $('#image').attr('src', "/api/file/download?file="+data.image);
      form.val("commodity", JSON.parse(JSON.stringify(data)));
    });
  }
</script>
</body>
</html>